#include "mymodel.h"

MyModel::MyModel(QObject *parent)
    : QAbstractListModel(parent)
{
    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, [&]
    {
        if(currentIndex>=0 && currentIndex<list.size())
        {
            MyData data = list.at(currentIndex);
            QFontMetrics fmt(Delegate::mFont);
            int width = fmt.width(data.name);
            if(width > Delegate::itemWidth)
            {
                data.x -= step;

                if(data.x < -width)
                {
                    data.x = Delegate::itemWidth;
                }
            }
            else
                timer->stop();
            upadteData(currentIndex, data);
        }
    });
    timer->start(100);
}

int MyModel::rowCount(const QModelIndex &parent) const
{
    if (parent.isValid())
        return 0;

    return list.count();
}

QVariant MyModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
        return QVariant();

    if(role == Role_Name)
        return list[index.row()].name;
    else if(role == Role_Type)
        return list[index.row()].isFold;
    else if(role == Role_Path)
        return list[index.row()].path;
    else if(role == Role_X)
        return  list[index.row()].x;
    else if(role == Role_Select)
        return list[index.row()].isSelect;
    else if(role == Role_Scroll)
        return list[index.row()].isScroll;
    else if(role == Role_FontSize)
        return list.at(index.row()).fontSize;
    return QVariant();
}

void MyModel::addData(MyData data)
{
    beginInsertRows(QModelIndex(), 0, 1);
    list.push_front(data);
    endInsertRows();
}

void MyModel::upadteData(int index, MyData data)
{
    list.replace(index, data);
    dataChanged(createIndex(index, 0), createIndex(index, 0));
}

void MyModel::deleteData(int index)
{
    if(list.size() && index < list.size())
    {
        beginRemoveRows(QModelIndex(), index, index-1);
        list.removeAt(index);
        endRemoveRows();
    }
}

void MyModel::clearData()
{
    beginResetModel();
    list.clear();
    endResetModel();
}

void MyModel::indexChange(int index)
{
    if(currentIndex != index && index < list.size())
    {
        MyData data;
        if(currentIndex>=0 && currentIndex<list.size())
        {
            data = list.at(currentIndex);
            data.isSelect = false;
            data.x = 0;
            upadteData(currentIndex, data);
        }

        data = list.at(index);
        data.isSelect = true;
        data.x = 0;
        upadteData(index, data);

        currentIndex = index;
        timer->start(100);
    }
}

MyData MyModel::getCurrentData()
{
    if(currentIndex>=0 && currentIndex<list.size())
    {
        return list.at(currentIndex);
    }
    return MyData{};
}

